package com.chen.pfm.slice;

import com.chen.pfm.ResourceTable;
import com.chen.pfm.entity.ResultVo;
import com.chen.pfm.entity.Statements;
import com.chen.pfm.utils.*;
import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import java.io.IOException;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;


public class BudgetManagementAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "BudgetManagementAbilitySlice");

    private String Budget;//填写得到的
    private TextField setYourBudget;//填写预算的框输入
    private Text CurrentMonth;//当前月份
    Statements currentMonthBudget;
    Button edit_but;
    Button confirm_btn;

    private Text currentBudget;//当前预算
    private Text remainingBudget;//剩余预算

    double monthincome;
    double monthspending;
    //预算
    double budget;

    private Text MonthSpending;//当月支出
    private Text Monthincome;//当月收入
    private Text Monthbalance;//当月结余
    //网络
    ResultVo resultVo;
    boolean flag;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_budget_management);
        flag = false;
        //当月报表
        int uid = Integer.valueOf(DataBaseUtil.GetValue(this, "uid"));

        String sdate = DateUtils.getStrCurrentYearandMonth();
        //当月报表
        currentMonthBudget = StatementsDBUtil.queryMonthStatements(this, uid, sdate);

        monthspending = intent.getDoubleParam("MonthSpending", 0);
        monthincome = intent.getDoubleParam("Monthincome", 0);


        //如果不存在，那么就插入一个当月的报表
        if (currentMonthBudget == null) {

            currentMonthBudget = new Statements(uid);
            currentMonthBudget.setSid(MyUtil.randomUUID());
            currentMonthBudget.setSdate(sdate);
            currentMonthBudget.setUid(uid);
            //然后同步到远端
            int insert = StatementsDBUtil.insert(this, currentMonthBudget);
            if (insert > 0) {
                MyToast.showMyToast(this, "当月报表初始化完成！");
            } else {
                return;
            }
        }
        //渲染上组件的获取
        //当月支出
        MonthSpending = (Text) findComponentById(ResourceTable.Id_MonthSpending);
        //当月收入
        Monthincome = (Text) findComponentById(ResourceTable.Id_Monthincome);
        //当月结余
        Monthbalance = (Text) findComponentById(ResourceTable.Id_Monthbalance);
        //当月预算
        currentBudget = (Text) findComponentById(ResourceTable.Id_currentBudget);
        //剩余预算
        remainingBudget = (Text) findComponentById(ResourceTable.Id_remainingBudget);

        //当前月份
        CurrentMonth = (Text) findComponentById(ResourceTable.Id_CurrentMonth);

        //数据渲染
        //日期渲染
        CurrentMonth.setText(sdate);
        //当月花费渲染
        MonthSpending.setText(MyUtil.getStrBalance(monthspending));
        //当月收入
        Monthincome.setText(MyUtil.getStrBalance(monthincome));
        //当月结余
        Monthbalance.setText(MyUtil.getStrBalance(monthspending - monthincome));

        //当月预算
        currentBudget.setText(MyUtil.getStrBalance(currentMonthBudget.getBudget()));
        //本月可用
        remainingBudget.setText(MyUtil.getStrBalance(currentMonthBudget.getBudget() - monthspending));

        //返回按钮监听
        findComponentById(ResourceTable.Id_goback_btn).setClickedListener((component) -> {
            terminate();
        });


        //编辑按钮
        edit_but = (Button) findComponentById(ResourceTable.Id_edit_but);
        edit_but.setClickedListener(this::setBudget);
        //保存按钮按钮
        confirm_btn = (Button) findComponentById(ResourceTable.Id_confirm_btn);
        confirm_btn.setClickedListener(this::updateData);
    }

    private void updateData(Component component) {

        if (!flag) {
            MyToast.showMyToast(this, "请先更新预算！");
            return;
        }
        try {
            int update = StatementsDBUtil.update(this, currentMonthBudget);
            if (update > 0) {
                MyToast.showMyToast(this, "本地预算更新成功！");
                //开一个线程更新信息
                updateRemoteData(MyUtil.updateBudgetByUid, currentMonthBudget);
            }
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }

    }

    private void updateRemoteData(String url, Object sendJsonObject) {
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
            ResultVo resultVo;
            Gson gson = new Gson();
            String sendjson = gson.toJson(sendJsonObject);
            String getRequestjson = null;
            //转化为json
            try {
                getRequestjson = HttpRequestUtil.sendPostRequestByOkHttp(url, sendjson);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (getRequestjson == null || getRequestjson.contains("not found")) {
                HiLog.info(LABEL, "无法连接到网络！");
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, "无法连接到网络");
                });
                return;
            } else {
                try {
                    resultVo = gson.fromJson(getRequestjson, ResultVo.class);
                } catch (Exception e) {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "gson解析返回对象失败，请确定服务器是否开启");
                    });
                    HiLog.error(LABEL, "有网络但是连接不到服务器时返回数据为：" + getRequestjson);
                    return;
                }
                if (resultVo == null) {//返回对象进行解析
                    HiLog.info(LABEL, "返回对象为空！");
                    //刷新页面上的数据，同样有一个坑，onChange方法实质上，在一个子线程里执行
                    getUITaskDispatcher().asyncDispatch(() -> {
                        //在这里执行页面ui组件的显示刷新
                        MyToast.showMyToast(this, "返回为空,数据丢失！");
                    });

                } else {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        //在这里执行页面ui组件的显示刷新
                        MyToast.showMyToast(this, "状态码" + resultVo.getCode() + " " + resultVo.getMsg());
                        if (resultVo.getCode() == 200) {
                        }
                    });
                }
            }
        });

    }

    private void setBudget(Component component) {
        //布局加载
        Component parse = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_dialog_textfield_layout_input, null, false);
        //创建显示气窗
        CommonDialog dialog = new CommonDialog(this);
        dialog.setOffset(0, 10);
        dialog.setContentCustomComponent(parse);
        dialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
        //取消按钮
        Button cancel = (Button) parse.findComponentById(ResourceTable.Id_logout_cancel);
        //确定按钮
        Button ok = (Button) parse.findComponentById(ResourceTable.Id_logout_ok);
        //预算设置的输入框
        setYourBudget = (TextField) parse.findComponentById(ResourceTable.Id_TextField);

        setYourBudget.setText(currentBudget.getText());

        //ui刷新线程显示
        getUITaskDispatcher().asyncDispatch(() -> {
            dialog.show();
            cancel.setClickedListener(c -> {
                dialog.destroy();
                MyToast.showMyToast(this, "已取消");

            });
            ok.setClickedListener(c -> {
                //你的预算
                Budget = setYourBudget.getText();
                if (Budget == null || "".equals(Budget)) {
                    HiLog.error(LABEL, "你输入的预算为空！");
                    MyToast.showMyToast(this, "预算不能为空");
                    return;
                }
                //  这里可以做非法检测l
                boolean moneyNumber = MyUtil.isMoneyNumber(Budget);
                if (!moneyNumber) {
                    MyToast.showMyToast(this, "预算输入不合法");
                    return;
                }
                //设置当前预算,刷新当前预算
                budget = MyUtil.getDoubleBalancefromStr(Budget);
                if (currentMonthBudget.getBudget() == budget) {
                    flag = false;
                } else {
                    flag = true;
                }
                currentBudget.setText(MyUtil.getStrBalance(budget));
                currentMonthBudget.setBudget(budget);
                //这里要从数据库从得到支出，如何让预算减去支出，刷新剩余预算
                remainingBudget.setText(MyUtil.getStrBalance(currentMonthBudget.getBudget() - monthspending));

                dialog.hide();
            });
        });
    }

    @Override
    public void onActive() {
        //ui线程刷新页面
        getUITaskDispatcher().asyncDispatch(() -> {

        });

        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {

    }
}
